<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/29 0029
 * Time: 上午 9:12
 */

namespace app\common\model;

use think\Model;
use think\Db;
use think\Request;


class Base extends Model
{

    //自定义初始化
    protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        //TODO:自定义的初始化
        $this->request = Request::instance();
    }


    /**
     * 操作数据表+数据
     * @param $Model 模型的实例化
     * @parma $type 操作数据的类型
     * @param $new_data 表单中提交的数据 主键值必须为  id
     * @param $url 要跳转的新路径
     * @parma $old_data 如果是编辑,则需要提交原有数据
     * @param  $primary_key 数据表中的主键值,默认情况下为id
     * @param  $adminType 当前平台的定义 1=后台 2=医生
     * @param  $isJump 当前是跳转还是查看
     * @param 返回数组
     **/

    public static function operaTable(Base $Model, $userId, $type = 'add', $new_data = [], $url = '', $old_data = [], $attach_arr, $primary_key = 'id', $adminType = 1, $isJump = true)
    {
        $model = clone $Model;
        $record_id = '';

        switch ($type) {
            case "add":
                $record_id = DB::name($model->table)->strict(false)->insertGetId($new_data);
                if ($model->table == "patient") {
                    $url = '/doctor/' . $url . "/pid/$record_id";
                }
                break;
            case "edit":
                $record_id = $new_data['id'];
                $model->allowField(true)->save($new_data, [$primary_key => $new_data['id']]);
                //  print_r($result);
                break;
            case "del":
                $where[$primary_key] = $new_data['id'];
                // $field = $model::getAttachArrBaseTableFields($attach_arr);
                $relate_data = array();
                $relate_data = DB::name($model->table)->field("*")->where($where)->find();
                if (!$relate_data) {
                    $relate_data = [];
                }

                $new_data = array_merge($relate_data, $new_data);
                $record_id = $new_data['id'];
                break;
            case "detail":
                $record_id = $new_data['id'];
                break;
        }

        //获取附属表单之后的
        //如果没有附属表,则不需要对应数据
        if ($attach_arr) {
            //  print_r($new_data);
            // exit;
            $new_data = $model::getDataFieldByAttachArr($attach_arr, $new_data);
        }

        /*  print_r($record_id);
          print_r($new_data);
           exit;*/
        //保存数据

        $result_id = $model->save_admin_log($userId, $model, $type, $record_id, $new_data, $old_data, $adminType);
        if ($isJump) {
            if ($result_id) {
                return ['flag' => 'success', 'msg' => '操作成功', 'url' => $url, 'record_id' => $record_id];
            } else {
                return ['flag' => 'error', 'msg' => '操作失败', 'url' => ''];
            }

        } else {
            return ['flag' => 'fetch', 'msg' => '操作成功', 'url' => ''];
        }

    }


    /**
     * 记录后台的操作日志
     * @param $admin_id ,用户的id
     * @param $content 操作行为
     * @param $log_url 操作的路径
     * @param $return 返回数据表中的id
     */
    public function add_admin_log($admin_id, $arr_content, $record_id, $table_name, $t_zh, $admin_type = 1)
    {

        //获取log_url
        $data = [
            'admin_id' => $admin_id,
            'content' => $arr_content['string'],
            'opera_table' => $table_name,
            'record_id' => $record_id,
            'table_zh' => $t_zh,
            'opera_type' => $arr_content['opera_type'],
            'admin_type' => $admin_type,
            //  'type' => $type
        ];

        //  print_r($data);

        $resultId = DB::name('admin_log')->insertGetId($data);
        return $resultId;
    }


    /**
     *保存log
     * @param $adminId 操作人员的id
     * @param $type 操作类型
     * @param $form_data  数据表中的数据
     * @param $old_data 数据表中原有的数据
     * @param $return 返回正确或false
     */

    public static function save_admin_log($adminId,Base $Model,$type='check',$record_id='',$form_data=[],$old_data=[],$admin_type=1){

        $model = clone $Model;
        $mysql_data = $model->getDataByMysql();

        //根据获取的表中的字段+form表单提交的数据+旧有数据+操作方式获取日志内容
        $arr = $model->getStringContentByDataAndMysql($Model, $mysql_data, $form_data, $old_data, $type);
        //  print_r($arr);
        //   exit;
        //添加数据
        $table_name = $mysql_data['t_name'];
        $t_zh = $mysql_data['model'];
        $adminLogId = $model->add_admin_log($adminId, $arr, $record_id, $table_name, $t_zh, $admin_type);
        if ($adminLogId) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据编辑的表单+改动的字段生成字符串
     * @param $mysql_data 数据库数据字段
     * @param $form_data  表单的提交数据
     * @param $old_data 数据表中的原有数据,即在做编辑的时候使用
     * @param $type 表单类型
     * @param $return 返回字符串
     **/
    protected static function getStringContentByDataAndMysql($Model, $mysql_data, $form_data = [], $old_data = [], $type = 'add')
    {
        $string = '';
        $return_string = '';
        $arr = [];
        $opera_type = '';
        $model = clone $Model;

        switch ($type) {
            case "check":
                $return_string = "查看" . $mysql_data['model'];
                $opera_type = 1;
                break;
            case 'detail':
                $string = "查看";
                $opera_type = 1;
                $return_string = '';
                foreach ($mysql_data as $key => $val) {
                    if (isset($form_data[$key])) {

                        if ($json_arr = $model->analyJson($val)) {

                            $return_string .= $json_arr[$form_data[$key]] . ',';
                        } else {
                            $return_string .= $val . ":" . $form_data[$key] . ',';
                        }
                    }
                }
                $return_string .= "的记录";
                break;
            case "add":
                $string = "添加";
                $opera_type = 2;
                $return_string = '';
                foreach ($mysql_data as $key => $val) {
                    if (isset($form_data[$key])) {
                        if ($json_arr = $model->analyJson($val)) {


                            $return_string .= $json_arr[$form_data[$key]] . ',';

                        } else {
                            $return_string .= $val . ":" . $form_data[$key] . ',';
                        }


                    }
                }
                break;
            case "edit":
                $return_string = '修改';
                $opera_type = 3;
                foreach ($mysql_data as $key => $val) {
                    if (isset($old_data[$key]) && isset($form_data[$key])) {

                        if ($json_arr = $model->analyJson($val)) {

                            $return_string .= $json_arr[$old_data[$key]] . "->" . $json_arr[$form_data[$key]] . ',';
                        } else {
                            $return_string .= $val . ':(' . $old_data[$key] . "->" . $form_data[$key] . '),';
                        }
                    }
                }
                break;
            case "del":
                $opera_type = 4;
                $return_string = $mysql_data['model'] . '删除';
                foreach ($mysql_data as $key => $val) {
                    if (isset($form_data[$key])) {
                        if ($json_arr = $model->analyJson($val)) {


                            $return_string .= $json_arr[$form_data[$key]] . ',';

                        } else {
                            $return_string .= $val . ":" . $form_data[$key] . ',';
                        }


                    }
                }
                break;
        }

        $string .= $return_string;
        // print_r($string);
        $arr = [
            'string' => $string,
            'opera_type' => $opera_type
        ];
        return $arr;
    }


    /**
     * 获取原有数据,多表关联
     * @param $base_id 查找基本数据表中主键值的数据
     * @param $base_arr 基础表中的数据 格式
     * [
     *  'table' => 'tableName',
     * 'field' => 'which filed you want select',
     * 'primary_key' => 'the primary_key name in table'
     * ]
     *[
     *  'table' => 'tableName',
     * 'field' => 'which filed you want select',
     * 'primary_key' => 'the primary_key name in table',
     * 'base_table_field' => 'the relation in base_table'
     * ]
     * @param $attach_arr 如果基础表中的有关联的其他表,则以数组的形式展示,多个表,则多个数组[[1],[2],[3]]
     * @param $old_data 返回原有数组
     */
    public static function getOneOldDataByTables($base_id, $base_arr, $attach_arr = [])
    {
        //查看元数据

        $table = $base_arr['table'];
        $field = $base_arr['field'];
        $where[$base_arr['primary_key']] = $base_id;
        $old_data = DB::name($table)
            ->field($field)
            ->where($where)->find();

        if (!empty($attach_arr)) {

            $old_data = Base::getDataFieldByAttachArr($attach_arr, $old_data);
        }


        return $old_data;
    }


    /***
     * 获取附件中数据表的数据
     * @param $tableName 数据表
     * @param $relate_field 关联的字段
     * @param $base_data 基础数据表的数组
     * @param $field 要在数据表中查找的字段
     * @param $relate_field 字符创
     */
    protected static function getOneFieldFromAttachTable($tableName, $relate_field, $base_data, $field, $primary_key = 'id')
    {
        //如果是顶级,则退出
        if (!isset($base_data[$relate_field])) {
            return false;
        }
        if ($base_data[$relate_field] == 0) {
            $relate_field = '顶级';
        } else {
            //换取附属表的相关信息
            $field_attach = $field;
            $where_attach[$primary_key] = $base_data[$relate_field];
            // print_r($where_attach);
            $attach_data = DB::name($tableName)
                ->field($field)
                ->where($where_attach)->find();
            /* print_r( DB::name($tableName)->getLastSql());
             print_r( $attach_data);
             print_r( $field_attach);
            exit;*/

            if ($attach_data) {
                $relate_field = $attach_data[$field_attach];
            }
        }

        return $relate_field;
    }

    /**
     * 根据附件数组,获取相应字段代表的中文含义
     * @param $attach_arr 附属表的数组
     * @param $form_data 表单中的数据
     * @param $form_data 返回数据
     * @parm return $form_data 数组
     */
    protected static function getDataFieldByAttachArr($attach_arr, $form_data)
    {

        foreach ($attach_arr as $attach_key => $attach_val) {
            $tableName = $attach_val['table'];
            $relate_field = $attach_val['base_table_field'];
            $field = $attach_val['field'];
            $primary_key = $attach_val['primary_key'];
            $relate_field = Base::getOneFieldFromAttachTable($tableName, $relate_field, $form_data, $field, $primary_key);

            $form_data[$attach_val['base_table_field']] = $relate_field;
            /*print_r( $attach_val['base_table_field']);
            print_r($form_data);*/
            //  exit;
        }

        return $form_data;
    }

    /**
     * 根据附属数组,获取其要查找在base数据表中的字段
     * @param $attach_arr 附属数组
     * @param $relate_field 字符串
     **/
    protected static function getAttachArrBaseTableFields($attach_arr)
    {
        $relate_field = '';
        foreach ($attach_arr as $attach_key => $attach_val) {
            $relate_field .= $attach_val['base_table_field'] . ',';
        }

        $relate_field = substr($relate_field, 0, -1);

        return $relate_field;

    }


    /**
     * 查看当前数据是否是json
     * @param $json_str json字符串
     * @param $return 返回数组
     * @param $result 返回数组
     */
    protected function analyJson($json_str)
    {

        $json_str = str_replace('＼＼', '', $json_str);

        $out_arr = array();

        preg_match('/{.*}/', $json_str, $out_arr);

        if (!empty($out_arr)) {
            $result = json_decode($out_arr[0], TRUE);

            // $result = $json_str;
        } else {

            return FALSE;

        }

        return $result;

    }


    /**
     * 根据基本表单的id,获取你要获取的手机号,前提是有关联表的情况下
     * @param $record_id 基础表中记录的id
     * @param $base_arr 基础表数组
     * @param $sendMsgAttach 要获取手机号的关联数组
     * @param return $sendMsgName 手机号  多个手机号以逗号分隔
     **/
    public static function getOneFieldByTablesToSendMsg($record_id, $base_arr, $sendMsgAttach)
    {
        //查看元数据
        $sendMsgName = '';
        $table = $base_arr['table'];
        $sendMsgTable = $sendMsgAttach['table'];
        $field = $sendMsgAttach['field'];
        $new_record_arr = array();
        //若是单记录变为数组
        if (!is_array($record_id)) {
            $new_record_arr[0] = $record_id;
        }

        foreach ($new_record_arr as $key => $re) {

            $where[$table . '.' . $base_arr['primary_key']] = $re;
                if (isset($sendMsgAttach['base_table_field'])) {
                    $string = $sendMsgTable . '.' . $sendMsgAttach['primary_key'] . '=' . $table . '.' . $sendMsgAttach['base_table_field'];

                    $sendMsgNameArr = DB::name($table)
                        ->field($field)
                        ->join($sendMsgTable, $string)
                        ->where($where)->find();
                } else {

                    // print_r($string);
                    $sendMsgNameArr = DB::name($table)
                        ->field($field)
                        ->where($where)->find();
                }
                if ($sendMsgNameArr) {
                    $phone = $sendMsgNameArr[$field];
                }
                if (count($record_id) == 1) {
                    $sendMsgName = $phone;

                } elseif ($key == count($record_id) - 1) {
                    $sendMsgName = $sendMsgName . $phone;

                } else {
                    $sendMsgName = $sendMsgName . $phone . ',';

                }

            }

        return $sendMsgName;


    }
}
